const errorType = require("../constans/error-types");
const md5password = require("../utils/password-handle");
const User = require("../model/user.model");
const { logger } = require("../../logger");

const verifyUser = async (ctx, next) => {
  // 1. 参数验证
  ctx.verifyParams({
    username: { type: "string", required: true },
    password: { type: "string", required: true },
    name: { type: "string", required: true },
    phone: { type: "string", required: true },
    permission: { type: "int", required: true },
  });

  try {
    const { username } = ctx.request.body;
    // 判断这次注册的用户名有没有被注册过
    const result = await User.findOne({
      where: { username },
    });
    if (result) {
      const error = new Error(errorType.USER_ALREADY_EXISTS);
      return ctx.app.emit("error", error, ctx);
    }
    await next();
  } catch (error) {
    logger.error(error);
    console.log(error);
  }
};

const handlePassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  ctx.request.body.password = md5password(password);

  await next();
};

module.exports = {
  verifyUser,
  handlePassword,
};
